#!/usr/bin/env python
# coding=utf-8

import traceback
import ConfigParser

from flask import Flask
from flask import request, make_response, redirect

from wechat_sdk import WechatBasic
from WXBizMsgCrypt import WXBizMsgCrypt

from lib import parser


app = Flask(__name__)
CONF = "config.ini"
token = None
wechat = None


@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        signature = request.args.get("msg_signature")
        timestamp = request.args.get("timestamp")
        nonce = request.args.get("nonce")
        echostr = request.args.get("echostr")
        return make_response(echostr, 200)

    if request.method == "POST":
        try:
            wechat.parse_data(request.data)
            if wechat.message.type == "text":
                msg = wechat.message.content
                user = wechat.message.source
            elif wechat.message.type == "voice":
                msg = wechat.message.recognition
                user = wechat.message.source

            print("%s: %s" % (user, msg))
            ret_msg = parser.handle_content(msg, user)
            xml = wechat.response_text(content=ret_msg)
            return make_response(xml, 200)
        except Exception as e:
            print(traceback.format_exc())
            ret_msg = "ah oh, 瓶子君没听懂哦~"
            xml = wechat.response_text(content=ret_msg)
            return make_response(xml, 200)



def get_token():
    c = ConfigParser.RawConfigParser()
    c.read(CONF)
    return c["server"]["token"]


if __name__ == "__main__":
    wechat = WechatBasic(token=token)
    app.debug = True
    app.run(host="0.0.0.0", port=80)
